package com.csii.test.sm;


import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
/**
 * sm4加密算法工具类
 * @explain sm4加密、解密与加密结果验证
 *          可逆算法
 * @author 
 * @creationTime 
 * @version 1.0
 * @since
 * @email 
 */
public class Sm4Util {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    
    public static final String SECKEY="372c7f1a49ff4b9a85d2da599332920f";     //测试密钥
    
    
    public static final String SECKEYFORNOTIFY="51ce8d809bdc47b3b6120701814dc0c4";     //测试密钥
    
    public static final String SECKEYFORYLB="f3273f8a333a4777b9e12fa9b8f4c336";     //测试密钥
    
    public static final String SECKEYFOROPENOS="51ce8d809bdc47b3b6120701814dc0c4";     //测试密钥
    
    private static final String ENCODING = "UTF-8";
    public static final String ALGORITHM_NAME = "SM4";
    // 加密算法/分组加密模式/分组填充方式
    // PKCS5Padding-以8个字节为一组进行分组加密
    // 定义分组加密模式使用：PKCS5Padding
    public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";
    // 128-32位16进制；256-64位16进制
    public static final int DEFAULT_KEY_SIZE = 128;

    /**
     * 生成ECB暗号
     * @explain ECB模式（电子密码本模式：Electronic codebook）
     * @param algorithmName
     *            算法名称
     * @param mode
     *            模式
     * @param key
     * @return
     * @throws Exception
     */
    private static Cipher generateEcbCipher(String algorithmName, int mode, byte[] key) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
        Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
        cipher.init(mode, sm4Key);
        return cipher;
    }


    /**
     * 自动生成密钥
     * @explain
     * @return
     * @throws NoSuchAlgorithmException
     * @throws NoSuchProviderException
     */
    public static byte[] generateKey() throws Exception {
        return generateKey(DEFAULT_KEY_SIZE);
    }

    /**
     * @explain
     * @param keySize
     * @return
     * @throws Exception
     */
    public static byte[] generateKey(int keySize) throws Exception {
        KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME, BouncyCastleProvider.PROVIDER_NAME);
        kg.init(keySize, new SecureRandom());
        return kg.generateKey().getEncoded();
    }

    
    /**
     * sm4加密
     * @explain 加密模式：ECB
     *          密文长度不固定，会随着被加密字符串长度的变化而变化
     * @param paramStr
     *            待加密字符串
     * @return 返回16进制的加密字符串
     * @throws Exception
     */
    public static String encryptEcb(String paramStr) throws Exception {
    	 return encryptEcb(SECKEY,paramStr);
    }
    
    
    public static String encryptEcbForNotify(Map postMap) throws Exception {
    	JSONObject dataobj = JSONObject.parseObject(JSON.toJSONString(postMap));
    	String sSrc = dataobj.toString();
    	System.out.println(sSrc);
    	return encryptEcb(SECKEYFORNOTIFY,sSrc);
    }
    
    public static String encryptEcbForYLB(Map postMap) throws Exception {
    	JSONObject dataobj = JSONObject.parseObject(JSON.toJSONString(postMap));
    	String sSrc = dataobj.toString();
    	return encryptEcb(SECKEYFORYLB,sSrc);
    }
    
    public static String encryptEcbForOpenOS(String paramStr) throws Exception {
    	return encryptEcb(SECKEYFOROPENOS,paramStr);
    }
    
    public static String sm3Sign(Map postMap) throws Exception{
    	Map signMap = new HashMap();
    	signMap.putAll(postMap);
    	signMap.put("open_key", SECKEYFORYLB);
    	String sortStr = Util.sort(signMap);
    	return SM3Digest.digestSM3(sortStr);
    }
    
    

    /**
     * sm4加密
     * @explain 加密模式：ECB
     *          密文长度不固定，会随着被加密字符串长度的变化而变化
     * @param hexKey
     *            16进制密钥（忽略大小写）
     * @param paramStr
     *            待加密字符串
     * @return 返回16进制的加密字符串
     * @throws Exception
     */
    public static String encryptEcb(String hexKey, String paramStr) throws Exception {
        String cipherText = "";
        // 16进制字符串-->byte[]
        byte[] keyData = ByteUtils.fromHexString(hexKey);
        // String-->byte[]
        byte[] srcData = paramStr.getBytes(ENCODING);
        // 加密后的数组
        byte[] cipherArray = encrypt_Ecb_Padding(keyData, srcData);
        // byte[]-->hexString
        cipherText = ByteUtils.toHexString(cipherArray);
        return cipherText;
    }

    /**
     * 加密模式之Ecb
     * @explain
     * @param key
     * @param data
     * @return
     * @throws Exception
     */
    public static byte[] encrypt_Ecb_Padding(byte[] key, byte[] data) throws Exception {
        Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(data);
    }

    /**
     * sm4解密
     * @explain 解密模式：采用ECB
     * @param cipherText
     *            16进制的加密字符串（忽略大小写）
     * @return 解密后的字符串
     * @throws Exception
     */
    public static String decryptEcb(String cipherText) throws Exception {
    	return decryptEcb(SECKEY, cipherText);
    }
    
    /**
     * sm4解密
     * @explain 解密模式：采用ECB
     * @param cipherText
     *            16进制的加密字符串（忽略大小写）
     * @return 解密后的字符串
     * @throws Exception
     */
    public static String decryptEcbForYLB(String cipherText) throws Exception {
    	return decryptEcb(SECKEYFORYLB, cipherText);
    }
    
    /**
     * sm4解密
     * @explain 解密模式：采用ECB
     * @param cipherText
     *            16进制的加密字符串（忽略大小写）
     * @return 解密后的字符串
     * @throws Exception
     */
    public static String decryptEcbForOpenOS(String cipherText) throws Exception {
    	return decryptEcb(SECKEYFOROPENOS, cipherText);
    }
    
    /**
     * sm4解密
     * @explain 解密模式：采用ECB
     * @param hexKey
     *            16进制密钥
     * @param cipherText
     *            16进制的加密字符串（忽略大小写）
     * @return 解密后的字符串
     * @throws Exception
     */
    public static String decryptEcb(String hexKey, String cipherText) throws Exception {
        // 用于接收解密后的字符串
        String decryptStr = "";
        // hexString-->byte[]
        byte[] keyData = ByteUtils.fromHexString(hexKey);
        // hexString-->byte[]
        byte[] cipherData = ByteUtils.fromHexString(cipherText);
        // 解密
        byte[] srcData = decrypt_Ecb_Padding(keyData, cipherData);
        // byte[]-->String
        decryptStr = new String(srcData, ENCODING);
        return decryptStr;
    }

    /**
     * 解密
     * @explain
     * @param key
     * @param cipherText
     * @return
     * @throws Exception
     */
    public static byte[] decrypt_Ecb_Padding(byte[] key, byte[] cipherText) throws Exception {
        Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(cipherText);
    }
    public static boolean verifyEcb(String hexKey, String cipherText, String paramStr) throws Exception {
        // 用于接收校验结果
        boolean flag = false;
        // hexString-->byte[]
        byte[] keyData = ByteUtils.fromHexString(hexKey);
        // 将16进制字符串转换成数组
        byte[] cipherData = ByteUtils.fromHexString(cipherText);
        // 解密
        byte[] decryptData = decrypt_Ecb_Padding(keyData, cipherData);
        // 将原字符串转换成byte[]
        byte[] srcData = paramStr.getBytes(ENCODING);
        // 判断2个数组是否一致
        flag = Arrays.equals(decryptData, srcData);
        return flag;
    }


    public static void main(String[] args) {
        try {
        	
        	String mw ="95162010763P058|A2021011908888392185|1|20210119|20210119100101|2088002384487224";
        	String sMw = Sm4Util.encryptEcbForOpenOS(mw);
        	System.out.println(sMw);
        	System.out.println(Sm4Util.decryptEcbForOpenOS("427c8319cb2704582a874c8e0826793fb6ea27bad50fa6919c6f7b8027518185738f338df8601ec621b8b80134185bc922dde06f65401163825a5ab9cf13b9f7f80f65601780de5f3dab3f39d8aac601"));
        	
        	
        	System.out.println(Sm4Util.decryptEcb("13a38f187f2549beb3abdb4044c88479", "f806126cdeb5ca656236819bb49691b7"));
        	
        	
        	
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    
    public static void ylbCheck(Map postMap) throws Exception{
    	//验签及解密  1、取data sm3对比
    	Map sm3Map = new HashMap();
    	sm3Map.put("open_id",postMap.get("open_id"));
		sm3Map.put("timestamp", postMap.get("timestamp"));
		sm3Map.put("data", postMap.get("data"));
    	
		if(postMap.get("sign").equals(Sm4Util.sm3Sign(sm3Map))){
			//SM4 解密
			String mwString = Sm4Util.decryptEcbForYLB((String)postMap.get("data"));
			System.out.println(mwString);
			
		}
		
    }
}